﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Topro.Application.Impl
{
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Product;
    using Topro.Entity.Response.Product;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 物料业务接口实现
    /// </summary>
    public class ProductServiceImpl: ProductService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public ProductServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取物料
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public ProductResponse Get(int? id)
        {
            var product = new ProductResponse();

            if (id.HasValue)
            {
                product = _db.DbConnection.QueryFirst<ProductResponse>("select * from t_product where Id=@Id", new { Id = id });
            }
            return product;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var user = _db.DbConnection.QueryFirst<ProductResponse>("select * from t_product where Id=@Id", new { Id = id });
                if (user == null)
                {
                    throw new Exception("物料记录不存在.");
                }

                var updateSql = "UPDATE t_product SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveProduct(ProductSaveRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (!string.IsNullOrEmpty(request.Id))
            {
                var productNameExist = _db.DbConnection.Query<Product>("SELECT * FROM t_product WHERE Name=@Name AND Id!=@Id", new { Name = request.Name, request.Id });
                if (productNameExist != null && productNameExist.Any())
                {
                    throw new Exception("物料名称已存在.");
                }

                var product = _db.DbConnection.QueryFirst<Product>("select * from t_product where Id=@Id", new { Id = request.Id });
                if (product == null)
                {
                    throw new Exception("物料记录不存在.");
                }

                product.Name = request.Name;
                product.Code = request.Code;
                product.Barcode = request.Barcode;
                product.Spec = request.Spec;
                //长mm
                if (!string.IsNullOrEmpty(request.Length))
                {
                    product.Length = int.Parse(request.Length);
                }
                else
                {
                    product.Length = null;
                }
                //宽mm
                if (!string.IsNullOrEmpty(request.Width))
                {
                    product.Width = int.Parse(request.Width);
                }
                else
                {
                    product.Width = null;
                }
                //高mm
                if (!string.IsNullOrEmpty(request.Height))
                {
                    product.Height = int.Parse(request.Height);
                }
                else
                {
                    product.Height = null;
                }
                //重量
                if (!string.IsNullOrEmpty(request.Weight))
                {
                    product.Weight = int.Parse(request.Weight);
                }
                else
                {
                    product.Weight = null;
                }
                //直径mm
                if (!string.IsNullOrEmpty(request.Diameter))
                {
                    product.Diameter = int.Parse(request.Diameter);
                }
                else
                {
                    product.Diameter = null;
                }
                //体积
                if (!string.IsNullOrEmpty(request.Volume))
                {
                    product.Volume = int.Parse(request.Volume);
                }
                else
                {
                    product.Volume = null;
                }
                product.Remark = request.Remark;
                product.Status = request.Status.Value;
                //product.DisplayOrder = int.Parse(request.DisplayOrder);
                product.CreatedBy = request.CreatedBy;
                product.CreateTime = DateTime.Now;

                //更新
                _db.DbConnection.Update<Product>(product);
                //日志
                _loggerService.Add(new OperLog()
                {
                    Level = 1,
                    Source = 1,
                    Message = @$"更新物料[{product.Name}]成功",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });
                response.Success = true;
            }
            else
            {
                var permissionNameExist = _db.DbConnection.Query<Product>("SELECT * FROM t_product WHERE Name=@Name", new { Name = request.Name });
                if (permissionNameExist != null && permissionNameExist.Any())
                {
                    throw new Exception("物料名称已存在.");
                }

                var product = new Product()
                {
                    Name = request.Name,
                    Code = request.Code,
                    Barcode = request.Barcode,
                    Spec = request.Spec,
                    Remark = request.Remark,
                    //DisplayOrder = int.Parse(request.DisplayOrder),
                    Status = request.Status.Value,
                    CreatedBy = request.CreatedBy,
                    CreateTime = DateTime.Now
                };

                //长mm
                if (!string.IsNullOrEmpty(request.Length))
                {
                    product.Length = int.Parse(request.Length);
                }
                //宽mm
                if (!string.IsNullOrEmpty(request.Width))
                {
                    product.Width = int.Parse(request.Width);
                }
                //高mm
                if (!string.IsNullOrEmpty(request.Height))
                {
                    product.Height = int.Parse(request.Height);
                }
                //重量
                if (!string.IsNullOrEmpty(request.Weight))
                {
                    product.Weight = int.Parse(request.Weight);
                }
                //直径mm
                if (!string.IsNullOrEmpty(request.Diameter))
                {
                    product.Diameter = int.Parse(request.Diameter);
                }
                //体积
                if (!string.IsNullOrEmpty(request.Volume))
                {
                    product.Volume = int.Parse(request.Volume);
                }
                //新增
                var resultId = _db.DbConnection.Insert<Product>(product);
                if (resultId <= 0)
                {
                    throw new Exception("新增物料失败.");
                }

                //日志
                _loggerService.Add(new OperLog()
                {
                    Level = 1,
                    Source = 1,
                    Message = @$"新增物料[{product.Name}]成功",
                    Exception = "",
                    Ip = request.Ip,
                    CreatedBy = request.UserId
                });

                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<ProductQueryResponse> GetPager(ProductQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,Name,Code,Barcode,Spec,Length,Width,Height,Weight,Diameter,Remark,Volume,Status,DisplayOrder,CreatedBy,CreateTime";
            var tableName = "t_product";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            if (!string.IsNullOrEmpty(query.Name))
            {
                where += string.Format(" And Name like'%{0}%'", query.Name);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<ProductQueryResponse>();

                return new DataGrid<ProductQueryResponse>()
                {
                    Rows = list,
                    Total = count
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<ProductQueryResponse> ProductQuery(ProductQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Name,Code,Barcode,Remark,Status,DisplayOrder,CreatedBy,CreateTime";
            var tableName = "t_product";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            if (query.Id.HasValue)
            {
                where += string.Format(" And Id ={0}", query.Id.Value);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var total = multi.ReadFirst<int>();

                var list = multi.Read<ProductQueryResponse>();

                return new DataGrid<ProductQueryResponse>()
                {
                    Rows = list,
                    Total = total
                };
            }
        }
    }
}
